const Router = require("koa-router");
const { Activity } = require("@models/activity");
const { Enroll } = require("@models/enroll");
const { Auth } = require("@middlewares/auth");
const { Op } = require("sequelize");
const { sequelize } = require("@core/db");
const { User } = require("@models//user");
const { wxPay } = require("@services/pay");
const { redis } = require("@core/redis");
const { ImgService } = require("@services/img");

const router = new Router({
  prefix: "/v1/activity",
});

// 获取活动列表
router.post("/list", new Auth().m, async (ctx, next) => {
  const { page, pageSize, title = "" } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = {
    condition: { [Op.lte]: ctx.auth.scope }, // 权限
    is_destroy: true,
    title: { [Op.like]: `%${title}%` },
  };
  const { count: total, rows } = await Activity.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [
      ["sort", "DESC"],
      ["created_at", "DESC"],
    ], // 排序
    attributes: { exclude: ["content"] },
    include: [
      {
        model: Enroll,
        attributes: ["uid"],
        required: false,
      },
    ],
  });
  let data = JSON.parse(JSON.stringify(rows)).map((v) => {
    let { Enrolls, ...res } = v;
    let enroll = v.Enrolls.find((v) => v.uid === ctx.auth.uid);
    return { ...res, is_enroll: !!enroll };
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: data,
  };
});

// 获取活动详情
router.post("/detail", async (ctx, next) => {
  const { activity_id } = ctx.request.body;

  const result = await redis.get(`activity:${activity_id}`);
  if (result) {
    ctx.body = {
      code: 200,
      msg: "获取成功",
      data: JSON.parse(result),
    };
  }
  if (!result) {
    const activity = await Activity.findOne({
      where: { activity_id, is_destroy: true },
    });
    const enroll = await Enroll.findAndCountAll({
      where: { activity_id },
      include: [
        {
          model: User,
          attributes: ["uid", "avatar"],
          required: false,
        },
      ],
    });

    if (!activity) {
       throw new global.errs.NotFound("活动不存或已下架");
    } else {
      let data = { activity, enroll: enroll.rows.map((v) => v.User) };

      await redis.set(`activity:${activity_id}`, JSON.stringify(data));
      ctx.body = {
        code: 200,
        msg: "获取成功",
        data: { ...data, is_enroll: !!enroll },
      };
    }
  }
});

// 活动报名
router.post("/enroll", new Auth().m, async (ctx, next) => {
  const { activity_id } = ctx.request.body;
  const t = await sequelize.transaction();
  const isEnroll = await Enroll.findOne(
    {
      where: {
        activity_id,
        uid: ctx.auth.uid,
      },
    },
    { transaction: t }
  );

  if (isEnroll) {
    await t.rollback();
    throw new global.errs.AuthFailed("该用户已报名");
  }

  const activity = await Activity.findOne(
    {
      where: {
        activity_id,
      },
    },
    { transaction: t }
  );
  if (!activity) {
    await t.rollback();
    throw new global.errs.AuthFailed("活动查询失败");
  }

  const user = await User.findOne(
    {
      where: {
        uid: ctx.auth.uid,
      },
    },
    { transaction: t }
  );
  if (!user) {
    await t.rollback();
    throw new global.errs.AuthFailed("用户查询失败");
  }

  let { content, ...activity_data } = JSON.parse(JSON.stringify(activity));
  activity_data.image = await ImgService.getImg64(activity_data.image);
  const enroll = await Enroll.create(
    {
      title: activity.title,
      admin_id: activity.admin_id,
      uid: ctx.auth.uid,
      activity_id,
      price: activity.price,
      activity_details: JSON.stringify(activity_data),
    },
    { transaction: t }
  );

  if (!enroll) {
    await t.rollback();
    throw new global.errs.AuthFailed("报名失败");
  }
  await t.commit();
  let data = {
    openid: user.openid,
    total: activity.price,
    description: activity.title,
    out_trade_no: enroll.enroll_number,
  };
  const result = await wxPay.Jsapi(data, ctx);
  await redis.del(`activity:${activity_id}`);
  ctx.body = {
    code: 200,
    msg: "报名成功",
    data: result,
  };
});

router.post("/base", async (ctx, next) => {
  const { img } = ctx.request.body;
  const res = await ImgService.getImg64(img);
  ctx.body = res;
});
// 报名详情
router.post("/enroll/detail", new Auth().m, async (ctx, next) => {
  const { enroll_number } = ctx.request.body;
  const enroll = await Enroll.findOne({
    where: { enroll_number },
    include: [
      {
        model: Activity,
        required: false,
      },
      {
        model: User,
        attributes: ["uid", "user_name", "avatar"],
        required: false,
      },
    ],
  });
  if (!enroll) {
    throw new global.errs.AuthFailed("查询失败");
  }
  ctx.body = {
    code: 200,
    msg: "获取成功",
    data: enroll,
  };
});



module.exports = router;
